<template>
  <div class="cr-box">
    <xr-create
      :loading="loading"
      :title="title"
      :isCol="false"
      :width="wkFlowList ? '984px' : '722px'"
      :confirm-button-text="sureBtnTitle"
      :showConfirm="!this.showFlow"
      @close="close"
      @save="saveClick"
    >
      <div class="d-flex" style="border-top: 16px solid #f6f7fc">
        <div
          style="width: 254px; border-right: 16px solid #f6f7fc"
          class="mt-20"
          v-if="wkFlowList"
        >
          <create-sections title="审核信息">
            <template slot="header">
              <el-tooltip
                v-if="flowRemarks"
                :content="flowRemarks"
                effect="dark"
                placement="top"
              >
                <i class="wk wk-help wk-help-tips" style="margin-left: 8px" />
              </el-tooltip>
            </template>
            <wk-approval-flow-apply :data="wkFlowList" style="padding: 15px" />
          </create-sections>
        </div>
        <div style="width: 714px" class="mt-20">
          <create-sections title="基本信息">
            <wk-form
              ref="crmForm"
              :model="fieldForm"
              :rules="fieldRules"
              :field-from="fieldForm"
              :field-list="fieldList"
              label-position="top"
              @change="formChange"
            >
              <template slot-scope="{ data }">
                <crm-relative-cell
                  v-if="data && data.formType == 'student'"
                  :value="fieldForm[data.field]"
                  :disabled="data.disabled"
                  relative-type="vipStudents"
                  @value-change="otherChange($event, data)"
                />
                <crm-relative-cell
                  v-if="data && data.formType == 'contract'"
                  :value="fieldForm[data.field]"
                  :disabled="data.disabled"
                  :relation="data.relation"
                  :relative-type="data.formType"
                  :ref-type="'refund'"
                  @value-change="otherChange($event, data)"
                />

                <crm-relative-cell
                  v-if="data && data.formType == 'receivables'"
                  :value="fieldForm[data.field]"
                  :disabled="data.disabled"
                  :relation="data.relation"
                  :relative-type="data.formType"
                  @value-change="otherChange($event, data)"
                />
              </template>
            </wk-form>
          </create-sections>
        </div>
      </div>
      <el-button
        slot="footer"
        type="primary"
        plain
        @click.native="debouncedSaveField(true)"
        >保存草稿</el-button
      >
    </xr-create>
  </div>
</template>

<script>
import { filedGetFieldAPI } from "@/api/crm/common";
import { crmRefundSaveAPI } from "@/api/crm/refund";

import XrCreate from "@/components/XrCreate";
import CreateSections from "@/components/CreateSections";
import WkForm from "@/components/NewCom/WkForm";
import { XhReceivablesPlan, CrmRelativeCell } from "@/components/CreateCom";
import WkApprovalFlowApply from "@/components/Examine/WkApprovalFlowApply";
import WkApprovalFlowApplyMixin from "@/components/Examine/mixins/WkApprovalFlowApply";
import crmTypeModel from "@/views/crm/model/crmTypeModel";
import CustomFieldsMixin from "@/mixins/CustomFields";
import { debounce } from "throttle-debounce";
import { objDeepCopy } from "@/utils";
import { queryContractByStudentId } from "@/api/crm/contract";
import { mapGetters } from "vuex";
export default {
  // 新建编辑
  name: "RefundCreate",
  components: {
    XrCreate,
    CreateSections,
    CrmRelativeCell,
    XhReceivablesPlan,
    WkApprovalFlowApply,
    WkForm,
  },

  mixins: [CustomFieldsMixin, WkApprovalFlowApplyMixin],

  props: {
    action: {
      type: Object,
      default: () => {
        return {
          type: "save",
          id: "",
          data: {},
        };
      },
    },
  },

  data() {
    return {
      loading: false,
      baseFields: [],
      fieldList: [],
      oldfieldList: [],
      fieldForm: {},
      fieldRules: {},

      // 审批信息
      flowRemarks: "",
      wkFlowList: null, // 有值有审批流
      curMode: null,
      showFlow: true,
    };
  },

  computed: {
    ...mapGetters(["userInfo"]),
    title() {
      return this.action.type === "update" ? "编辑退款" : "新建退款";
    },

    editId() {
      return this.action.type == "update" ? this.action.id : "";
    },

    // 确认名称
    sureBtnTitle() {
      if (this.wkFlowList) {
        return "提交审核";
      }
      return "保存";
    },
  },

  watch: {},

  created() {
    this.debouncedSaveField = debounce(300, this.saveClick);

    this.getField();
  },

  mounted() {},

  beforeDestroy() {},

  methods: {
    /**
     * 获取数据
     */

    getField() {
      this.loading = true;
      const params = {
        label: crmTypeModel.refund,
      };
      if (this.action.type == "update") {
        params.id = this.action.id;
      }
      filedGetFieldAPI(params)
        .then((res) => {
          const list = res.data || [];

          const fieldList = [];
          const fieldRules = {};
          const fieldForm = {};
          let studentVal = [];
          list.forEach((item) => {
            const temp = {};
            temp.field = item.fieldName;
            temp.formType = item.formType;
            temp.fieldId = item.fieldId;
            temp.inputTips = item.inputTips;
            temp.name = item.name;
            temp.setting = item.setting;
            temp.restrictData = item.restrictData;
            if (item.formType === "leve_linkage") {
              //多级下拉option
              temp.levelData = item.levelData;
            }
            if (item.fieldName === "vipPeriods") {
              temp.maxlength = item.maxLength;
            }

            if (temp.formType == "single_user") {
              // 人员选择 课程讲师
              if (temp.field == "teacherId") {
                temp.isTeacher = true;
              } else {
                temp.isTeacher = false;
              }
            }
            const canEdit = this.getItemIsCanEdit(item, this.action.type);
            // 是否能编辑权限
            if (canEdit) {
              // 自动生成编号
              if (item.autoGeneNumber == 1) {
                temp.placeholder = "根据编号规则自动生成，支持手动输入";
                const copyItem = objDeepCopy(item);
                copyItem.isNull = 0;
                fieldRules[temp.field] = this.getRules(copyItem);
              } else {
                fieldRules[temp.field] = this.getRules(item);
              }
            }

            // 是否可编辑
            temp.disabled = !canEdit;

            // 禁止某些业务组件选择
            if (
              temp.formType == "receivables_plan" ||
              temp.formType == "contract" ||
              temp.formType == "customer" ||
              temp.formType == "student" ||
              temp.formType == "number_input" ||
              temp.formType == "receivables"
            ) {
              if (this.action.type == "relative") {
                const relativeDisInfos = {
                  contacts: { customer: true },
                  customer: { customer: true },
                  business: { customer: true },
                  contract: { customer: true, contract: true },
                  receivables: {
                    customer: true,
                    contract: true,
                    receivables: true,
                  },
                };
                // 在哪个类型下添加
                const relativeTypeDisInfos =
                  relativeDisInfos[this.action.crmType];
                if (relativeTypeDisInfos) {
                  // 包含的字段值
                  temp.disabled = relativeTypeDisInfos[item.formType] || false;
                }
              } else if (this.action.type != "update") {
                temp.disabled =
                  item.formType === "contract" ||
                  item.formType === "receivables_plan" ||
                  item.formType === "number_input" ||
                  item.formType === "receivables";
              } else if (this.action.type == "update") {
                temp.disabled = item.formType === "number_input";
              }
            }

            if (temp.formType === "number_input") {
              temp.disabled = item.formType === "number_input";
            }
            if (temp.formType == "contract") {
              temp.disabled = true;
            }
            // 处理关联
            if (
              this.action.type == "relative" ||
              this.action.type == "update"
            ) {
              // 回款计划 需要合同信息
              if (item.formType === "receivables_plan") {
                const contractItem = this.getItemRelatveInfo(list, "contract");
                if (contractItem) {
                  contractItem["moduleType"] = "contract";
                  temp["relation"] = contractItem;
                }
                // 合同 需要学员信息
              } else if (item.formType == "contract") {
                const customerItem = this.getItemRelatveInfo(list, "student");
                if (customerItem) {
                  customerItem["moduleType"] = "customer";
                  customerItem["params"] = { checkStatus: 1 };
                  temp["relation"] = customerItem;
                }
              } else if (item.formType == "receivables") {
                const contractItem = this.getItemRelatveInfo(list, "contract");
                if (contractItem) {
                  contractItem["moduleType"] = "contract";
                  contractItem["params"] = { checkStatus: 1 };
                  temp["relation"] = contractItem;
                }
              }
            }

            // 特殊字段允许多选
            this.getItemRadio(item, temp);

            // 获取默认值
            fieldForm[temp.field] = this.getItemValue(
              item,
              this.action.data,
              this.action.type
            );
            // console.log("测试打印temp.field----------------");
            // console.log(temp.field);
            if (this.action.type != "update") {
              //创建退款时，回显合同相关信息
              if (temp.field == "studentId") {
                let val = this.getItemValue(
                  item,
                  this.action.data,
                  this.action.type
                );
                if (val.length > 0) {
                  studentVal = val;
                  temp.disabled = true;
                }
              }
            }
            if (this.action.type != "update") {
              if (item.fieldName == "refundUserId") {
                fieldForm["refundUserId"] = this.userInfo.userId;
              }
            }
            fieldList.push(temp);
          });
          this.baseFields = list;
          this.fieldList = fieldList;
          this.fieldList.forEach((fieldItem) => {
            if (fieldItem.formType === "contract") {
              if (studentVal.length > 0) {
                this.getContractVal(studentVal);
              }
            }
          });
          this.fieldForm = fieldForm;
          console.log("测试打印----------------编辑");
          console.log(this.fieldForm);
          this.fieldRules = fieldRules;

          this.oldfieldList = fieldList;

          this.huixian();
          // 审核信息
          this.initWkFlowData(
            {
              params: { label: 13 },
              fieldForm: this.fieldForm,
            },
            (res) => {
              this.showFlow = false;
              this.wkFlowList = res.list;
              this.flowRemarks = res.resData ? res.resData.remarks : "";
            }
          );

          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },

    huixian() {
      if (this.fieldForm.refundType === "原路退回") {
        let arr = [];
        this.oldfieldList.forEach((item) => {
          if (
            item.field != "bankCardMsg" &&
            item.field != "mapBankcardaddr" &&
            item.field != "bankCardNumber" &&
            item.field != "accountHolder" &&
            item.field != "subBankCardMsg"
          ) {
            arr.push(item);
          }
        });
        this.fieldList = arr;
      } else {
        this.fieldList = this.oldfieldList;
      }
    },
    /**
     * 保存
     */
    saveClick(isDraft = false) {
      this.loading = true;
      const crmForm = this.$refs.crmForm.instance;
      crmForm.validate((valid) => {
        if (valid) {
          const wkFlowResult = this.validateWkFlowData(this.wkFlowList);
          if (wkFlowResult.pass) {
            const params = this.getSubmiteParams(
              this.baseFields,
              this.fieldForm
            );
            if (isDraft) {
              params.entity.checkStatus = 5;
            }
            if (wkFlowResult.data) {
              params.examineFlowData = wkFlowResult.data;
            }
            this.submiteParams(params);
          } else {
            this.loading = false;
            this.$message.error("请完善审批信息");
          }
        } else {
          this.loading = false;
          // 提示第一个error
          this.getFormErrorMessage(crmForm);
          return false;
        }
      });
    },

    /**
     * 提交上传
     */
    submiteParams(params) {
      if (this.action.type == "update") {
        params.entity.refundId = this.action.id;
        params.entity.batchId = this.action.batchId;
      }

      // 相关添加时候的多余提交信息
      if (
        this.action.relativeData &&
        Object.keys(this.action.relativeData).length
      ) {
        params = { ...params, ...this.action.relativeData };
      }

      crmRefundSaveAPI(params)
        .then((res) => {
          this.loading = false;

          this.$message.success(
            this.action.type == "update" ? "编辑成功" : "添加成功"
          );

          this.close();

          // 保存成功
          this.$emit("save-success", {
            type: "receivables",
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 验证唯一
     */
    UniquePromise({ field, value }) {
      return this.getUniquePromise(field, value, this.action);
    },

    /**
     * change
     */
    formChange(field, index, value, valueList) {
      // 审批流逻辑
      this.debouncedGetWkFlowList(field.field, this.fieldForm);
      if (field.field === "refundType") {
        if (value === "原路退回") {
          let arr = [];
          this.oldfieldList.forEach((item) => {
            if (
              item.field != "bankCardMsg" &&
              item.field != "mapBankcardaddr" &&
              item.field != "bankCardNumber" &&
              item.field != "accountHolder" &&
              item.field != "subBankCardMsg"
            ) {
              arr.push(item);
            }
          });
          this.fieldList = arr;
        } else {
          this.fieldList = this.oldfieldList;
        }
        if (this.$refs.crmForm.$refs && this.$refs.crmForm.$refs.form) {
          this.$refs.crmForm.$refs.form.clearValidate();
        }
        // if(value === "原路退回"){
        //   this.fieldRules["bankCardMsg"] = {};
        //   this.fieldRules["mapBankcardaddr"] = {};
        //   this.fieldRules["bankCardNumber"] = {};
        //   this.fieldRules["accountHolder"] = {};
        // }else{
        //   this.fieldRules["bankCardMsg"] = {
        //     required: true,
        //     message: '银行卡信息不能为空',
        //     trigger: ['blur', 'change']
        //   };
        //   this.fieldRules["mapBankcardaddr"] = {
        //     required: true,
        //     message: '开户行所在地不能为空',
        //     trigger: ['blur', 'change']
        //   };
        //   this.fieldRules["bankCardNumber"] = {
        //     required: true,
        //     message: '银行卡号不能为空',
        //     trigger: ['blur', 'change']
        //   };
        //   this.fieldRules["accountHolder"] = {
        //     required: true,
        //     message: '开户人姓名不能为空',
        //     trigger: ['blur', 'change']
        //   };
        // }
      }
    },
    // 合同相关信息回显
    getContractVal(data) {
      let vipStudentInfo = data[0];
      console.log(vipStudentInfo,12312312);
      queryContractByStudentId({studentId: data[0].studentId}).then((res) => {
        if (res.code == 0) {
          if (res.data && res.data.contractId) {
            this.$set(this.fieldForm, "contractId", [res.data]);
            this.fieldList.forEach((fieldItem) => {
              if (fieldItem.field == "returnType") {
                this.$set(this.fieldForm, "returnType", res.data.returnType);
              }
              if (fieldItem.field == "returnTime") {
                this.$set(this.fieldForm, "returnTime", res.data.createTime);
              }
              if (fieldItem.field == "contractMoney") {
                this.$set(this.fieldForm, "contractMoney", res.data.money);
              }
              if (fieldItem.field == "ownerUserId") {
                this.$set(this.fieldForm, "ownerUserId", res.data.ownerUserId);
              }
              if (fieldItem.field == "teacherId") {
                this.$set(
                  this.fieldForm,
                  "teacherId",
                  // vipStudentInfo.teacherId
                  res.data.teacherId
                );
              }
            });
          } else {
            this.$set(this.fieldForm, "contractId", []);
          }
        }
      });
    },
    // 选了合同以后，其他项回显
    contractChange(data) {
      this.fieldList.forEach((fieldItem) => {
        if (fieldItem.formType === "receivables") {
          // 如果是合同 改变合同样式和传入学员ID
          if (data.value.length > 0) {
            fieldItem.disabled = false;
            const customerItem = data.value[0];
            customerItem["moduleType"] = "contract";
            customerItem["params"] = { checkStatus: 1 };
            fieldItem["relation"] = customerItem;
          } else {
            fieldItem.disabled = true;
            fieldItem["relation"] = {};
          }
          this.fieldForm[fieldItem.field] = [];
        }
        if (fieldItem.field === "returnType") {
          this.fieldForm[fieldItem.field] =
            data.value.length > 0 ? data.value[0].returnType : "";
        }
        if (fieldItem.field === "returnTime") {
          this.fieldForm[fieldItem.field] =
            data.value.length > 0 ? data.value[0].createTime : "";
        }
        if (fieldItem.field === "contractMoney") {
          this.fieldForm[fieldItem.field] =
            data.value.length > 0 ? data.value[0].money : "";
        }
        if (fieldItem.field === "platformNumber") {
          this.fieldForm[fieldItem.field] =
            data.value.length > 0 ? data.value[0].threePartOrderNo : "";
        }
        if (fieldItem.field == "ownerUserId") {
          this.fieldForm.ownerUserId =
            data.value instanceof Array
              ? data.value.length > 0 && data.value[0].ownerUserId
                ? Number(data.value[0].ownerUserId)
                : ""
              : this.fieldForm.ownerUserId;
        }
      });

      const planItem = this.fieldList.find(
        (item) => item.formType === "receivables"
      );
      if (planItem) {
        if (data.value.length > 0) {
          planItem.disabled = false;
          var contractItem = data.value[0];
          contractItem["moduleType"] = "contract";
          planItem["relation"] = contractItem;
        } else {
          planItem.disabled = true;
          planItem["relation"] = {};
        }
        this.fieldForm[planItem.field] = "";
      }
    },
    /**
     * 地址change
     */
    otherChange(data, field) {
      if (field.formType === "student") {
        if (data.value.length > 0) {
        } else {
          this.contractChange(data);
        }
        this.fieldList.forEach((fieldItem) => {
          fieldItem["relation"] = data.value[0];
          if (fieldItem.formType === "contract") {
            // 如果是合同
            if (data.value.length > 0) {
              this.getContractVal(data.value);
            }
            fieldItem.disabled = true;
            this.fieldForm[fieldItem.field] = [];

            // if (data.value.length > 0) {
            //   fieldItem.disabled = false;
            //   const customerItem = data.value[0];
            //   customerItem["moduleType"] = "customer";
            //   customerItem["params"] = { checkStatus: 1 };
            //   fieldItem["relation"] = customerItem;
            // } else {
            //   fieldItem.disabled = true;
            //   fieldItem["relation"] = {};
            //   this.fieldForm.contractId = []
            // }
          } else if (fieldItem.formType === "receivables_plan") {
            fieldItem.disabled = true;
            fieldItem["relation"] = {};
            this.fieldForm[fieldItem.field] = "";
          }
          // else if (fieldItem.field == "ownerUserId") {
          //   let str = data.value.length > 0 ? data.value[0].ownerUserId : "";
          //   if (str) {
          //       this.fieldForm.ownerUserId = Number(str);
          //   }
          // }
          // else if (fieldItem.field == "teacherId") {
          //   this.fieldForm.teacherId =
          //     data.value instanceof Array
          //       ? data.value.length > 0
          //         ? data.value[0].teacherId
          //         : ""
          //       : this.fieldForm.teacherId;
          // }
          else if (fieldItem.field == "vipPeriods") {
            this.fieldForm.vipPeriods =
              data.value.length > 0
                ? data.value[0].vipPeriods
                : (this.fieldForm.vipPeriods = "");
          }
        });
      } else if (field.formType === "contract") {
        this.contractChange(data);
      } else if (field.formType === "receivables_plan") {
        const dataValue = data.data || {};
        this.fieldForm.returnTime = dataValue.returnDate;
        this.fieldForm.money = dataValue.money;
        this.fieldForm.returnType = dataValue.returnType;
      } else if (field.formType === "receivables") {
        this.fieldList.forEach((fieldItem) => {
          //
          if (fieldItem.formType === "receivables") {
            if (data.value.length > 0) {
              fieldItem.disabled = false;
              const customerItem = data.value[0];
              customerItem["moduleType"] = "receivables";
              customerItem["params"] = { checkStatus: 1 };
              fieldItem["relation"] = customerItem;
            } else {
              fieldItem.disabled = true;
              fieldItem["relation"] = {};
            }
            this.fieldForm[fieldItem.field] = [];
            this.fieldForm.returnType = data.value[0].returnType;
          }
        });
      }
      this.$set(this.fieldForm, field.field, data.value);
      this.$refs.crmForm.instance.validateField(field.field);
    },

    /**
     * 关闭
     */
    close() {
      this.$emit("close");
    },
  },
};
</script>

<style lang="scss" scoped>
.wk-form {
  position: relative;
  /deep/ .el-form-item.is-product {
    flex: 0 0 100%;
    width: 0;
  }
}
.cr-box {
  position: relative;
  z-index: 3000;
}
/deep/ .c-icon {
  // position: absolute !important;
  // right: 300px !important;
  // bottom:50px !important
}
</style>
